<template>
    <div class="order-detail-container">
        <!-- 返回按钮 -->
        <button class="back-btn" @click="goBack">返回</button>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <p>正在加载订单详情...</p>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-state">
            <p>⚠️ 加载失败：{{ error }}</p>
            <button @click="fetchOrderDetails" class="retry-btn">重试</button>
        </div>

        <!-- 正常显示 -->
        <template v-else>
            <h2 class="page-title">订单详情</h2>

            <div class="order-card">
                <div class="order-info">
                    <p class="info-item" v-if="order">
                        <span class="label">订单号：</span>
                        {{ order.orderid }}
                    </p>
                    <p class="info-item">
                        <span class="label">总金额：</span>
                        ¥{{ (order?.totalprice || 0).toFixed(2) }}
                    </p>
                    <p class="info-item">
                        <span class="label">状态：</span>
                        <span class="status-badge" :class="statusClass">
                            {{ order?.status || '未知状态' }}
                        </span>
                    </p>
                    <p class="info-item">
                        <span class="label">客户ID：</span>
                        {{ order?.userid || '未知客户' }}
                    </p>
                    <p class="info-item">
                        <span class="label">收货地址：</span>
                        {{ order?.shipping_address || '未填写地址' }}
                    </p>
                    <p class="info-item">
                        <span class="label">下单时间：</span>
                        {{ formatDate(order?.createtime) }}
                    </p>
                </div>

                <h3 class="section-title">商品清单</h3>
                <div class="product-list">
                    <div v-for="product in products" :key="product.orderproductid" class="product-item">
                        <div class="product-image-wrapper">
                            <img :src="product.productimg || '/default-product.png'" :alt="product.title"
                                class="product-image" @error="handleImageError">
                        </div>
                        <div class="product-info">
                            <h4 class="product-title">{{ product.title }}</h4>
                            <p class="product-price">¥{{ product.price.toFixed(2) }}</p>
                            <div class="product-meta">
                                <span>×{{ product.quantity }}</span>
                                <span>小计：¥{{ (product.price * product.quantity).toFixed(2) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <el-button type="primary" @click="showUpdateStatusDialog">修改状态</el-button>

                <!-- 空状态 -->
                <div v-if="products.length === 0" class="empty-state">
                    <p>暂无商品信息</p>
                </div>
            </div>
        </template>

        <!-- 修改订单状态对话框 -->
        <el-dialog title="修改订单状态" v-model="updateStatusDialogVisible" width="30%">
            <el-form :model="order" label-width="100px">
                <el-form-item label="订单ID">
                    <el-input v-model="order.orderid" disabled></el-input>
                </el-form-item>
                <el-form-item label="当前状态">
                    <el-input v-model="order.status" disabled></el-input>
                </el-form-item>
                <el-form-item label="新状态">
                    <el-select v-model="newStatus" placeholder="选择新状态" required>
                        <el-option label="未支付" value="未支付"></el-option>
                        <el-option label="已支付" value="已支付"></el-option>
                        <el-option label="运输中" value="运输中"></el-option>
                        <el-option label="已完成" value="已完成"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updateStatusDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleUpdateOrderStatus">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { getOrderProductByOrderid, updateOrderStatus } from '../../api/order.js'

const route = useRoute()
const router = useRouter()

// 响应式数据
const order = ref(null)
const products = ref([])
const loading = ref(true)
const error = ref(null)
const updateStatusDialogVisible = ref(false)
const newStatus = ref('')

// 计算状态类
const statusClass = computed(() => {
    const status = order.value?.status?.toLowerCase()
    return {
        'paid': status === '已支付',
        'unpaid': status === '未支付',
        'transporting': status === '运输中',
        'completed': status === '已完成'
    }
})

// 图片加载失败处理
const handleImageError = (e) => {
    e.target.src = '/default-product.png'
}

// 日期格式化
const formatDate = (timestamp) => {
    if (!timestamp) return '-'
    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }
    return new Date(timestamp).toLocaleString('zh-CN', options)
}

// 获取订单数据
const fetchOrderDetails = async () => {
    try {
        loading.value = true
        error.value = null
        const orderId = route.params.orderid

        if (!orderId) {
            throw new Error('无效的订单ID')
        }

        const response = await getOrderProductByOrderid(orderId)

        if (response.data?.code === 1) {
            order.value = response.data.data?.order || null
            products.value = response.data.data?.orderWithProduct || []

            if (!order.value) {
                throw new Error('订单不存在')
            }
        } else {
            throw new Error(response.data?.msg || '获取订单失败')
        }
    } catch (err) {
        console.error('订单详情加载失败:', err)
        error.value = err.message || '网络请求失败，请稍后重试'
    } finally {
        loading.value = false
    }
}

// 显示修改订单状态对话框
const showUpdateStatusDialog = () => {
    newStatus.value = order.value.status;
    updateStatusDialogVisible.value = true;
};

// 修改订单状态
const handleUpdateOrderStatus = async () => {
    if (!newStatus.value) {
        error.value = '请选择新状态';
        return;
    }
    try {
        console.log('[修改订单状态] 请求参数:', order.value.orderid, newStatus.value);


        const response = await updateOrderStatus(order.value.orderid, newStatus.value);
        console.log('[修改订单状态] 完整响应对象:', response);
        if (response.data.code === 1) {
            console.log('订单状态修改成功:', response.data.msg);
            order.value.status = newStatus.value; // 更新本地订单状态
            updateStatusDialogVisible.value = false;
        } else {
            console.error('订单状态修改失败:', response.data.msg);
            error.value = response.data.msg;
        }
    } catch (err) {
        console.error('请求捕获异常:', err.message, '完整错误:', err);
        error.value = `网络错误: ${err.message}`;
    }
};

// 返回上一页
const goBack = () => {
    router.back()
}

// 组件挂载时恢复状态或获取数据
onMounted(() => {
    if (route.meta.savedState) {
        // 恢复保存的状态
        order.value = route.meta.savedState.order
        products.value = route.meta.savedState.products
        loading.value = route.meta.savedState.loading
        error.value = route.meta.savedState.error
        // 清除保存的状态
        route.meta.savedState = null
    } else {
        fetchOrderDetails()
    }
})

// 路由离开前保存状态
onBeforeRouteLeave((to, from) => {
    from.meta.savedState = {
        order: order.value,
        products: products.value,
        loading: loading.value,
        error: error.value
    }
})
</script>

<style scoped>
/* 基础样式 */
.order-detail-container {
    padding: 1rem;
    min-height: 100vh;
    background: #f5f5f5;
}

/* 返回按钮 */
.back-btn {
    margin-bottom: 1rem;
    padding: 8px 20px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.back-btn:hover {
    background-color: darken(#007bff, 10%);
}

/* 加载状态 */
.loading-state {
    text-align: center;
    padding: 2rem;
}

.spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 1rem;
    border: 3px solid #ddd;
    border-radius: 50%;
    border-top-color: #007bff;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* 错误状态 */
.error-state {
    text-align: center;
    padding: 2rem;
    color: #dc3545;
}

.retry-btn {
    margin-top: 1rem;
    padding: 8px 20px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

/* 订单卡片 */
.order-card {
    background: white;
    border-radius: 12px;
    padding: 1rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item {
    margin: 0.8rem 0;
    font-size: 0.95rem;
    line-height: 1.5;
}

.label {
    color: #666;
    min-width: 80px;
    display: inline-block;
}

/* 状态标签 */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 16px;
    font-size: 0.85rem;
}

.status-badge.paid {
    background: #e8f5e9;
    color: #2e7d32;
}

.status-badge.unpaid {
    background: #ffebee;
    color: #c62828;
}

.status-badge.transporting {
    background: #fff9c4;
    color: #f57f17;
}

.status-badge.completed {
    background: #e8eaf6;
    color: #3949ab;
}

/* 商品列表 */
.section-title {
    font-size: 1.2rem;
    margin: 1.5rem 0 1rem;
    color: #333;
}

.product-list {
    margin-top: 1rem;
}

.product-item {
    display: flex;
    gap: 1rem;
    padding: 1rem;
    margin-bottom: 1rem;
    background: #f8f9fa;
    border-radius: 8px;
}

.product-image-wrapper {
    flex: 0 0 100px;
    height: 100px;
    border-radius: 6px;
    overflow: hidden;
}

.product-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-info {
    flex: 1;
}

.product-title {
    font-size: 1rem;
    margin: 0 0 0.5rem;
    color: #333;
}

.product-price {
    color: #e4393c;
    font-weight: bold;
    margin: 0.3rem 0;
}

.product-meta {
    display: flex;
    justify-content: space-between;
    color: #666;
    font-size: 0.9rem;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .product-item {
        flex-direction: column;
    }

    .product-image-wrapper {
        flex: none;
        width: 100%;
        height: 150px;
    }

    .info-item {
        font-size: 0.9rem;
    }
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 2rem;
    color: #666;
}
</style>